const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const jwt = require("jsonwebtoken");
const expressJWT = require("express-jwt");
app.use(bodyParser.urlencoded({ extended: false }));

const secretKey = "itheiam No1";

// unless 里配置不需要访问权限 的路径
app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/api\//],
  })
);

app.get("/", (req, res) => {
  res.send("home page");
});

app.post("/api/login", (req, res) => {
  const userinfo = req.body;

  if (userinfo.username !== "admin" || userinfo.password !== "123456") {
    console.log("there is something wrong with the login ");
    return res.send({
      status: 400,
      msg: "登入失败",
    });
  }
  // jwt.sign()接收三个参数： 用户的信息对象， 加密的秘钥， 配置对象
  const token = jwt.sign({ username: userinfo.username }, secretKey, {
    expiresIn: "60s",
  });
  res.send({
    status: 200,
    msg: "登入成功",
    token: token,
  });
});

app.get("/admin/getinfo", (req, res) => {
  console.log(req.user);
  res.send({
    status: 200,
    msg: "获取用户信息成功",
    data: req.user,
  });
});

app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError ") {
    return res.send({
      status: 400,
      msg: "invalid token",
    });
  }
  res.send({
    status: 500,
    message: err.message,
  });
});

app.listen(80, () => {
  console.log("server is running ");
});
